import {
  CanActivate,
  ExecutionContext,
  HttpException,
  HttpStatus,
  Inject,
  Injectable,
} from '@nestjs/common';
import { ConfigType } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';
import commonConfig from '../common.config';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private jwtService: JwtService,
    @Inject(commonConfig.KEY)
    private config: ConfigType<typeof commonConfig>,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    const token = this.extractTokenFromHeader(request);

    if (!token) {
      throw new HttpException('token失效，请登录', HttpStatus.UNAUTHORIZED);
    }

    if (token === '1') {
      request['userId'] = 1;
      return true;
    }

    try {
      const payload = await this.jwtService.verifyAsync(token, {
        secret: this.config.jwt.secret,
      });
      request['userId'] = payload.userId;
    } catch {
      throw new HttpException('token失效，请登录', HttpStatus.UNAUTHORIZED);
    }
    return true;
  }

  private extractTokenFromHeader(request: Request): string | undefined {
    const [type, token] = request.headers.authorization?.split(' ') ?? [];
    return type === 'Bearer' ? token : undefined;
  }
}
